<?php
declare (strict_types = 1);

namespace app\validate;

use think\facade\Db;
use think\Validate;

class Examiner extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'name'=>['require'],
        'id_card'=>['require','uniqueIdCard:thinkphp'],
        'phone'=>['require','uniquePhone:thinkphp'],
        'school'=>['require'],
        'edu_back'=>['require'],
        'job_title'=>['require'],
        'major'=>['require'],
        'exam_major'=>['require'],
        'work_unit'=>['require'],
        'area'=>['require'],
        'address'=>['require']
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
        'name.require'=>'姓名不能为空',
        'id_card.require'=>'身份证不能为空',
        'id_card.uniqueIdCard'=>'此身份证号已被注册',
        'school.require'=>'毕业院校不能为空',
        'edu_back.require'=>'学历不能为空',
        'job_title.require'=>'职称不能为空',
        'major.require'=>'专业不能为空',
        'exam_major.require'=>'执考专业不能为空',
        'work_unit.require'=>'工作单位不能为空',
        'area.require'=>'所在地区不能为空',
        'address.require'=>'详细地址不能为空',
        'phone.require'=>'手机号不能为空',
        'phone.uniquePhone'=>'手机号已经被注册了',
        ];

    /**
     * 校验身份证号是否唯一
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     */
    protected function uniqueIdCard($value,$rule, array $data=[]):bool{
        $where =[
            ['id_card','=',$value]
        ];
        if(isset($data['id'])&& !empty($data['id'])){
            $where[]=['id','<>',$data['id']];
        }
//        print_r($where);
        $check = Db::name('examiner')->where($where)->count();
        return $check==0;
    }

    /**
     * 校验手机号是否唯一
     * @param $value
     * @param $rule
     * @param array $data
     * @return bool
     */
    protected function uniquePhone($value,$rule, array $data=[]):bool{
        $where =[
            ['phone','=',$value]
        ];
        if(isset($data['id'])&& !empty($data['id'])){
            $where[]=['id','<>',$data['id']];
        }
        $check = Db::name('examiner')->where($where)->count();
        return $check==0;
    }
}
